package com.wtwd.campus.h5_manager.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.h5_manager.common.Constant;
import com.wtwd.campus.h5_manager.common.PageDataVO;
import com.wtwd.campus.h5_manager.common.RespCode;
import com.wtwd.campus.h5_manager.common.RespEntity;
import com.wtwd.campus.h5_manager.entity.H5Deviceinfo;
import com.wtwd.campus.h5_manager.entity.H5ManageUser;
import com.wtwd.campus.h5_manager.service.H5DeviceManageService;
import com.wtwd.campus.h5_manager.service.H5ManagerUserService;
import com.wtwd.campus.h5_manager.service.H5UserDeviceService;
import com.wtwd.campus.utils.CommandNumberUtil;
import com.wtwd.campus.utils.CommandSendUtils;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author mjy
 * @date 2022/03/09
 * @description
 */
@Api(tags = "h5设备管理")
@RestController
@RequestMapping("/webH5-manage-device")
public class H5DeviceManageController {

    private static final Logger logger = LoggerFactory.getLogger(H5DeviceManageController.class);

    @Autowired
    private H5ManagerUserService managerUserService;

    @Autowired
    private H5DeviceManageService deviceManageService;

    @Autowired
    private H5UserDeviceService h5UserDeviceService;

    @Autowired
    private CommandSendUtils commandSendUtils;

    /**
     * 此处考虑是否加入威科姆设备
     *
     * @param currentPage
     * @param pageSize
     * @param imei
     * @param state
     * @param request
     * @return
     */
    @ApiOperation(value = "查询h5设备管理分页数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "页数", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "pageSize", value = "页大小", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "imei", value = "imei", dataType = "String", required = false)
            , @ApiImplicitParam(name = "state", value = "state", dataType = "int", required = false, example = "1:在线,2不在线")
    })
    @ApiResponses({@ApiResponse(code = 602, message = "无权操作")
    })
    @GetMapping("/queryDevicePage")
    public RespEntity<PageDataVO<H5Deviceinfo>> queryDevicePage(@RequestParam(value = "currentPage", defaultValue = "0") Integer currentPage,
                                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                                @RequestParam(value = "imei", required = false) String imei,
                                                                @RequestParam(value = "state", required = false) Integer state,
                                                                HttpServletRequest request
    ) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = managerUserService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("queryDevicePage userId={},currentPage={},pageSize={},imei={},state={}", userId, currentPage, pageSize, imei, state);
        H5ManageUser h5ManageUser = managerUserService.getUserById(userId);
        if (h5ManageUser == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        H5Deviceinfo searchDevice = new H5Deviceinfo();
        searchDevice.setImei(imei);
        searchDevice.setState(state);
        searchDevice.setCustomerId(h5ManageUser.getCustomerId());
        //此处redis性能消耗过大
        /*List<H5Deviceinfo> deviceinfos = deviceManageService.queryDeviceByConditions(searchDevice);
        Map<String, Object> map = this.disposalData(deviceinfos, currentPage, pageSize);
        H5DeviceInfoVo deviceInfoVo = new H5DeviceInfoVo();
        deviceInfoVo.setTotal((Integer) map.get("total"));
        List<H5Deviceinfo> deviceinfos1 = (List<H5Deviceinfo>) map.get("list");
        deviceInfoVo.setRows(deviceinfos1);
        return new RespEntity<>(RespCode.SUCCESS, deviceInfoVo);
        */
        long time = new Date().getTime() - Constants.OFF_LINE_TIME;
        searchDevice.setTime(time);
        Page<H5Deviceinfo> page = new Page<>(currentPage, pageSize);
        IPage<H5Deviceinfo> h5Deviceinfos = null;
        if (Constant.VCOM_CUSTOMER_ADMIN == h5ManageUser.getCustomerId()) {
            h5Deviceinfos = deviceManageService.queryVcomDeviceByConditionsPage(searchDevice, page);
        } else {
            h5Deviceinfos = deviceManageService.queryDeviceByConditionsPage(searchDevice, page);
        }
        return RespEntity.success(h5Deviceinfos);
    }


    /**
     * 新增h5设备
     *
     * @param h5DeviceInfo
     * @param request
     * @return
     */
    @ApiOperation(value = "新增h5设备")
    @PostMapping("/addDeviceInfo")
    public RespEntity addDeviceInfo(@RequestBody H5Deviceinfo h5DeviceInfo, HttpServletRequest request) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = managerUserService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("addDeviceInfo userId={},h5DeviceInfo={}", userId, h5DeviceInfo.toString());
        H5ManageUser h5ManageUser = managerUserService.getUserById(userId);
        if (h5ManageUser == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        if (StringUtils.isBlank(h5DeviceInfo.getImei()) || h5DeviceInfo.getCustomerId() == null||h5DeviceInfo.getIfScreen()==null||StringUtils.isBlank(h5DeviceInfo.getModel())) {
            return new RespEntity(RespCode.NO_PARAM);
        }
        Boolean authImei = deviceManageService.AuthImei(h5DeviceInfo.getImei());
        if (!authImei) {
            return new RespEntity(RespCode.DEVICE_EXIST);
        }
        if (h5ManageUser.getCustomerId() == Constant.VCOM_CUSTOMER_ADMIN||Constant.VCOM_CUSTOMER_ADMIN==h5DeviceInfo.getCustomerId()) {//如果超管添加的是vcom的设备,或者用户是vcom的,则设备类型为5
            h5DeviceInfo.setDeviceType(Constant.VCOM_DEVICE_TYPE);
        } else {
            h5DeviceInfo.setDeviceType(Constant.H5_DEVICE_TYPE);
        }
        h5DeviceInfo.setCreateTime(new Date().getTime());
        h5DeviceInfo.setUpdateTime(new Date().getTime());
        Integer rest = deviceManageService.addDeviceInfo(h5DeviceInfo);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 获取绑定人列表(根据设备号查询h5绑定人)
     * <p>
     * 绑定人手机号码拿不到
     *
     * @param
     * @return
     */
 /*   @GetMapping("/getH5BindUserByDeviceId/{deviceId}")
    public RespEntity<> getH5BindUserByDeviceId(@PathVariable Integer deviceId) {
        logger.info("getH5BindUserByDeviceId deviceId={}", deviceId);
         h5UserDeviceService.getH5BindUserByDeviceId(deviceId);

    }*/
    @ApiOperation(value = "删除设备信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceId", value = "设备id", required = true, dataTypeClass = Integer.class)
    })
    @DeleteMapping("/deleteDeviceInfo/{deviceId}")
    public RespEntity deleteDeviceInfo(@PathVariable Integer deviceId) {
        //根据设备id获取设备信息
        H5Deviceinfo device = deviceManageService.getDeviceInfoByDeviceId(deviceId);
        if (device == null) {
            return new RespEntity(RespCode.DEVICE_EXIST);
        }
        //删除设备数据
        Integer rest = deviceManageService.deleteDeviceById(deviceId);
        if (rest > 0) {
            //恢复设备出厂设置
            boolean online = commandSendUtils.deviceOnline(device.getImei());
            String commandNumber = CommandNumberUtil.getCurTime();
            boolean b = commandSendUtils.reSetDevice(device.getImei(), commandNumber, online, -2, false);
        }
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    private <T> Map<String, Object> disposalData(List<T> list, Integer curPage, Integer pageSize) {
        List<T> resultRecord = new ArrayList<>();
        Integer total = list.size();
        int start = curPage * pageSize;
        int end = start + pageSize;
        if (list.size() < start) {
            return null;
        }
        for (int i = start; i < (list.size() < end ? list.size() : end); i++) {
            resultRecord.add(list.get(i));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("list", resultRecord);
        return map;
    }


}
